package com.qt.leetcode;


import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class Demo03 {

    public static void main(String[] args) {
        int result = lengthOfLongestSubstring2("abcabcbb");
        System.out.println(result);
    }

    public static int lengthOfLongestSubstring2(String s) {
        if(s.length() == 0){
            return 0;
        }
        int remove = 0,max = 0;
        Map<Character, Integer> item = new HashMap<Character, Integer>();
        for (int i = 0; i < s.length(); i++) {
            if(item.containsKey(s.charAt(i))){
                remove = Math.max(remove,item.get(s.charAt(i)) + 1);
            }
            item.put(s.charAt(i),i);
            max = Math.max(max,i - remove + 1);
        }
        return max;

    }



    public static int lengthOfLongestSubstring(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max = 0;
        int left = 0;
        for(int i = 0; i < s.length(); i ++){
            if(map.containsKey(s.charAt(i))){
                //a bca c bcbb
                left = Math.max(left,map.get(s.charAt(i)) + 1);//每次都移出，重复元素位置的索引数
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-left+1);
        }
        return max;

    }


}
